package com.wangling.servlet;

import com.wangling.model.User;
import com.wangling.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/do-login")
public class DoLoginServlet extends HttpServlet {
    private final UserService userService = new UserService();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = userService.login(username, password);

        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html");
        PrintWriter writer = resp.getWriter();
        if (user != null) {
            HttpSession session = req.getSession();
            session.setAttribute("currentUser", user);
            writer.printf("<p>登录成功，点击<a href='/blog0124/'>此处</a>跳转首页<p/>\r\n");
        } else {
            writer.printf("\"<p>登陆失败，点击<a href='/blog0123/login.html'>此处</a>重新登陆</p>\\r\\n\"");
        }
    }
}
